{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
        "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/Segmentation/segmentation_snic.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/Segmentation/segmentation_snic.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/Segmentation/segmentation_snic.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Install Earth Engine API and geemap\n",
        "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://geemap.org). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
        "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Installs geemap package\n",
        "import subprocess\n",
        "\n",
        "try:\n",
        "    import geemap\n",
        "except ImportError:\n",
        "    print('Installing geemap ...')\n",
        "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import ee\n",
        "import geemap"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Create an interactive map \n",
        "The default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map = geemap.Map(center=[40,-100], zoom=4)\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Add Earth Engine Python script "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Add Earth Engine dataset\n",
        "# imageCollection = ee.ImageCollection(\"USDA/NAIP/DOQQ\"),\n",
        "# geometry = ee.Geometry.Polygon(\n",
        "#     [[[-121.89511299133301, 38.98496606984683],\n",
        "#         [-121.89511299133301, 38.909335196675435],\n",
        "#         [-121.69358253479004, 38.909335196675435],\n",
        "#         [-121.69358253479004, 38.98496606984683]]], {}, False),\n",
        "# geometry2 = ee.Geometry.Polygon(\n",
        "#     [[[-108.34304809570307, 36.66975278349341],\n",
        "#         [-108.34225416183466, 36.66977859999848],\n",
        "#         [-108.34226489067072, 36.67042400981031],\n",
        "#         [-108.34308028221125, 36.670380982657925]]]),\n",
        "# imageCollection2 = ee.ImageCollection(\"USDA/NASS/CDL\"),\n",
        "# cdl2016 = ee.Image(\"USDA/NASS/CDL/2016\")\n",
        "\n",
        "\n",
        "# Map.centerObject(geometry, {}, 'roi')\n",
        "# # Map.addLayer(ee.Image(1), {'palette': \"white\"})\n",
        "# cdl2016 = cdl2016.select(0).clip(geometry)\n",
        "\n",
        "# function erode(img, distance) {\n",
        "#   d = (img.Not().unmask(1) \\\n",
        "#        .fastDistanceTransform(30).sqrt() \\\n",
        "#        .multiply(ee.Image.pixelArea().sqrt()))\n",
        "#   return img.updateMask(d.gt(distance))\n",
        "# }\n",
        "\n",
        "# function dilate(img, distance) {\n",
        "#   d = (img.fastDistanceTransform(30).sqrt() \\\n",
        "#        .multiply(ee.Image.pixelArea().sqrt()))\n",
        "#   return d.lt(distance)\n",
        "# }\n",
        "\n",
        "# function expandSeeds(seeds) {\n",
        "#   seeds = seeds.unmask(0).focal_max()\n",
        "#   return seeds.updateMask(seeds)\n",
        "# }\n",
        "\n",
        "# bands = [\"R\", \"G\", \"B\", \"N\"]\n",
        "# img = imageCollection \\\n",
        "#     .filterDate('2015-01-01', '2017-01-01') \\\n",
        "#     .filterBounds(geometry) \\\n",
        "#     .mosaic()\n",
        "# img = ee.Image(img).clip(geometry).divide(255).select(bands)\n",
        "# Map.addLayer(img, {'gamma': 0.8}, \"RGBN\", False)\n",
        "\n",
        "# seeds = ee.Algorithms.Image.Segmentation.seedGrid(36)\n",
        "\n",
        "# # Apply a softening.\n",
        "# kernel = ee.Kernel.gaussian(3)\n",
        "# img = img.convolve(kernel)\n",
        "# Map.addLayer(img, {'gamma': 0.8}, \"RGBN blur\", False)\n",
        "\n",
        "# # Compute and display NDVI, NDVI slices and NDVI gradient.\n",
        "# ndvi = img.normalizedDifference([\"N\", \"R\"])\n",
        "# # print(ui.Chart.image.histogram(ndvi, geometry, 10))\n",
        "# Map.addLayer(ndvi, {'min':0, 'max':1, 'palette': [\"black\", \"tan\", \"green\", \"darkgreen\"]}, \"NDVI\", False)\n",
        "# Map.addLayer(ndvi.gt([0, 0.2, 0.40, 0.60, 0.80, 1.00]).reduce('sum'), {'min':0, 'max': 6}, \"NDVI steps\", False)\n",
        "# ndviGradient = ndvi.gradient().pow(2).reduce('sum').sqrt()\n",
        "# Map.addLayer(ndviGradient, {'min':0, 'max':0.01}, \"NDVI gradient\", False)\n",
        "\n",
        "# gradient = img.spectralErosion().spectralGradient('emd')\n",
        "# Map.addLayer(gradient, {'min':0, 'max': 0.3}, \"emd\", False)\n",
        "\n",
        "# # Run SNIC on the regular square grid.\n",
        "# snic = ee.Algorithms.Image.Segmentation.SNIC({\n",
        "#   'image': img,\n",
        "#   'size': 32,\n",
        "#   compactness: 5,\n",
        "#   connectivity: 8,\n",
        "#   neighborhoodSize:256,\n",
        "#   seeds: seeds\n",
        "# }).select([\"R_mean\", \"G_mean\", \"B_mean\", \"N_mean\", \"clusters\"], [\"R\", \"G\", \"B\", \"N\", \"clusters\"])\n",
        "\n",
        "# clusters = snic.select(\"clusters\")\n",
        "# Map.addLayer(clusters.randomVisualizer(), {}, \"clusters\")\n",
        "# Map.addLayer(snic, {'bands': [\"R\", \"G\", \"B\"], 'min':0, 'max':1, 'gamma': 0.8}, \"means\", False)\n",
        "# Map.addLayer(expandSeeds(seeds))\n",
        "\n",
        "# # Compute per-cluster stdDev.\n",
        "# stdDev = img.addBands(clusters).reduceConnectedComponents(ee.Reducer.stdDev(), \"clusters\", 256)\n",
        "# Map.addLayer(stdDev, {'min':0, 'max':0.1}, \"StdDev\")\n",
        "\n",
        "# # Display outliers as transparent\n",
        "# outliers = stdDev.reduce('sum').gt(0.25)\n",
        "# Map.addLayer(outliers.updateMask(outliers.Not()), {}, \"Outliers\", False)\n",
        "\n",
        "# # Within each outlier, find most distant member.\n",
        "# distance = img.select(bands).spectralDistance(snic.select(bands), \"sam\").updateMask(outliers)\n",
        "# maxDistance = distance.addBands(clusters).reduceConnectedComponents(ee.Reducer.max(), \"clusters\", 256)\n",
        "# Map.addLayer(distance, {'min':0, 'max':0.3}, \"max distance\")\n",
        "# Map.addLayer(expandSeeds(expandSeeds(distance.eq(maxDistance))), {'palette': [\"red\"]}, \"second seeds\")\n",
        "\n",
        "# newSeeds = seeds.unmask(0).add(distance.eq(maxDistance).unmask(0))\n",
        "# newSeeds = newSeeds.updateMask(newSeeds)\n",
        "\n",
        "# # Run SNIC again with both sets of seeds.\n",
        "# snic2 = ee.Algorithms.Image.Segmentation.SNIC({\n",
        "#   'image': img,\n",
        "#   'size': 32,\n",
        "#   compactness: 5,\n",
        "#   connectivity: 8,\n",
        "#   neighborhoodSize: 256,\n",
        "#   seeds: newSeeds\n",
        "# }).select([\"R_mean\", \"G_mean\", \"B_mean\", \"N_mean\", \"clusters\"], [\"R\", \"G\", \"B\", \"N\", \"clusters\"])\n",
        "# clusters2 = snic2.select(\"clusters\")\n",
        "# Map.addLayer(clusters2.randomVisualizer(), {}, \"clusters 2\")\n",
        "# Map.addLayer(snic2, {'bands': [\"R\", \"G\", \"B\"], 'min':0, 'max':1, 'gamma': 0.8}, \"means\", False)\n",
        "\n",
        "# # Compute outliers again.\n",
        "# stdDev2 = img.addBands(clusters2).reduceConnectedComponents(ee.Reducer.stdDev(), \"clusters\", 256)\n",
        "# Map.addLayer(stdDev2, {'min':0, 'max':0.1}, \"StdDev 2\")\n",
        "# outliers2 = stdDev2.reduce('sum').gt(0.25)\n",
        "# outliers2 = outliers2.updateMask(outliers2.Not())\n",
        "# Map.addLayer(outliers2, {}, \"Outliers 2\", False)\n",
        "\n",
        "# # Show the final set of seeds.\n",
        "# Map.addLayer(expandSeeds(newSeeds), {'palette': \"white\"}, \"newSeeds\")\n",
        "# Map.addLayer(expandSeeds(distance.eq(maxDistance)), {'palette': [\"red\"]}, \"second seeds\")\n",
        "\n",
        "# # Area, Perimeter, Width and Height (using snic1 for speed)\n",
        "# area = ee.Image.pixelArea().addBands(clusters).reduceConnectedComponents(ee.Reducer.sum(), \"clusters\", 256)\n",
        "# Map.addLayer(area, {'min':50000, 'max': 500000}, \"Cluster Area\")\n",
        "# minMax = clusters.reduceNeighborhood(ee.Reducer.minMax(), ee.Kernel.square(1))\n",
        "\n",
        "# perimeterPixels = minMax.select(0).neq(minMax.select(1)).rename('perimeter')\n",
        "# Map.addLayer(perimeterPixels, {'min': 0, 'max': 1}, 'perimeterPixels')\n",
        "\n",
        "# perimeter = perimeterPixels.addBands(clusters) \\\n",
        "#     .reduceConnectedComponents(ee.Reducer.sum(), 'clusters', 256)\n",
        "# Map.addLayer(perimeter, {'min': 100, 'max': 400}, 'Perimeter size', False)\n",
        "\n",
        "# sizes = ee.Image.pixelLonLat().addBands(clusters).reduceConnectedComponents(ee.Reducer.minMax(), \"clusters\", 256)\n",
        "# width = sizes.select(\"longitude_max\").subtract(sizes.select(\"longitude_min\"))\n",
        "# height = sizes.select(\"latitude_max\").subtract(sizes.select(\"latitude_min\"))\n",
        "# Map.addLayer(width, {'min':0, 'max':0.02}, \"Cluster width\")\n",
        "# Map.addLayer(height, {'min':0, 'max':0.02}, \"Cluster height\")\n"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Display Earth Engine data layers "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    }
  ],
  "metadata": {
    "anaconda-cloud": {},
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.1"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}